package com.oneday.nuo.base.security.user;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.oneday.nuo.base.entity.NuoUserEntity;
import com.oneday.nuo.base.service.NuoAuthService;
import com.oneday.nuo.base.service.NuoUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class NuoUserDetailsService implements UserDetailsService {
    @Autowired
    private NuoUserService nuoUserService;

    @Autowired
    private NuoAuthService nuoAuthService;

    /**
     * 获取用户信息
     * @Author: liushuai
     * @Date: 2021/2/9 18:53
     * @param : * @param userName  用户账号
     * @return :org.springframework.security.core.userdetails.UserDetails
     **/
    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        if(StrUtil.isEmpty(userName)){
            return null;
        }
        NuoUserEntity entity = nuoUserService.queryUserInfoByUserName(userName);
        if(ObjectUtils.isNull(entity) || entity.getId() == null){
            return null;
        }
        NuoUser user = Convert.convert(NuoUser.class, entity);
        //用户权限
        List<NuoAuth> auths = nuoAuthService.queryAuthByUserId(user.getId());
        user.setAuthorities(auths);
        return user;
    }

}
